package com.fyy.utils.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileToBase64 {

    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
    private FileToBase64(){}; //私有构造方法

    public static String fileToBase64(String str) throws IOException {
        logger.info("下载的文件地址：{}",str);
        URL url = new URL(str);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setConnectTimeout(3 * 1000);
        conn.setReadTimeout(60 * 1000);
        InputStream inputStream = conn.getInputStream();
        byte[] bytes = readInputStream(inputStream);
        String base64Str = new BASE64Encoder().encode(bytes);


        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Str);
        String s = writeBytesToFile(buffer,"D://test","zhaowei.jpg");
        logger.info("文件保存位置:{}",s);

        return base64Str;
    }

    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1){
            bos.write(buffer,0,len);
        }
        bos.close();
        return bos.toByteArray();
    }

    private static String writeBytesToFile(byte[] bytes,String filePath,String fileName) throws IOException {
        File dir = new File(filePath);
        if(!dir.exists()){
            dir.mkdir(); //不存在创建
        }
        File file = new File(filePath + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bytes);
        fos.close();
        return filePath + File.separator + fileName;
    }

    public static void main(String[] args) throws IOException {
        System.out.println(fileToBase64("https://p0.ssl.img.360kuai.com/t01fe7c6f87640133e7.webp"));
    }

}
